package gat.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bitsun.core.common.exception.AppException;
import com.tencentcloudapi.common.CommonClient;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import gat.RedisService;
import gat.common.config.TencentConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * @author 你先别说话
 * @date 2025/3/11
 */
@Slf4j
@Component
public class TencentUtils {

    @Autowired
    private TencentConfig tencentConfig;

    @Autowired
    private RedisService redisService;

    public String getPrimaryUId(String accountId) throws Exception {
        // 根据accountId 从缓存中查询 查询不到 再根据接口轮询 查询到之后 设置缓存
        String primaryUId = redisService.get("primary:tencent:" + accountId);
        if (StringUtils.isNotBlank(primaryUId)) {
            return primaryUId;
        }

        List<TencentConfig.TencentAccount> accounts = tencentConfig.getAccounts();
        for (TencentConfig.TencentAccount account : accounts) {
            try {
                JSONObject jsonObject = queryAccountInfo(account.getAccountId(), accountId);
                if (jsonObject != null) {
                    primaryUId = account.getAccountId();
                }
            } catch (Exception ex) {
                log.error("该账号的主账号不是："+account.getAccountId());
            }
        }
        if (StringUtils.isBlank(primaryUId)) {
            throw new AppException("该账号的主账号未查询到，请联系销售人员");
        }
        redisService.set("primary:tencent:" + accountId, primaryUId);
        return primaryUId;

    }

    public JSONObject queryAccountInfo(String primaryUid, String accountId) {
        try {
            CommonClient client = tencentConfig.createClient(primaryUid);
            String params = String.format("{\"FilterType\":\"ClientUin\",\"Filter\":\"%s\"}", accountId);
            String queryCustomersCredit = client.call("QueryCustomersCredit", params);
            JSONObject response = JSONObject.parseObject(queryCustomersCredit);
            JSONObject responseObj = response.getJSONObject("Response");
            JSONArray dataArray = responseObj.getJSONArray("Data");
            if (dataArray != null && !dataArray.isEmpty()) {
                return dataArray.getJSONObject(0);
            }
            return null;

        } catch (TencentCloudSDKException e) {
            throw new AppException("腾讯云账号查询异常");
        }
    }

    // 查询信控信息
    public JSONObject queryAccountInfo(String accountId) {
        try {
            String primaryUId = getPrimaryUId(accountId);
            CommonClient client = tencentConfig.createClient(primaryUId);
            String params = String.format("{\"FilterType\":\"ClientUin\",\"Filter\":\"%s\"}", accountId);
            String queryCustomersCredit = client.call("QueryCustomersCredit", params);
            JSONObject response = JSONObject.parseObject(queryCustomersCredit);
            JSONObject responseObj = response.getJSONObject("Response");
            JSONArray dataArray = responseObj.getJSONArray("Data");
            if (dataArray != null && !dataArray.isEmpty()) {
                return dataArray.getJSONObject(0);
            }
            return new JSONObject();

        } catch (Exception e) {
            throw new AppException("腾讯云账号查询异常");
        }
    }

    public JSONObject describeCustomerInfo(String accountId) {
        try {
            String primaryUId = getPrimaryUId(accountId);
            CommonClient client = tencentConfig.createClient(primaryUId);

            // 使用JSONObject构建参数，动态传入accountId
            JSONObject params = new JSONObject();
            JSONArray customerUins = new JSONArray();
            customerUins.add(Long.parseLong(accountId));
            params.put("CustomerUin", customerUins);

            String resp = client.call("DescribeCustomerInfo", params.toJSONString());
            JSONObject response = JSONObject.parseObject(resp);
            JSONObject responseObj = response.getJSONObject("Response");
            JSONArray dataArray = responseObj.getJSONArray("Data");

            if (dataArray != null && !dataArray.isEmpty()) {
                return dataArray.getJSONObject(0);
            }
            return new JSONObject();

        } catch (Exception e) {
            throw new AppException("腾讯云账号查询异常");
        }
    }

    public JSONObject describeCustomerInfo(String primaryUId, String accountId) {
        try {
            CommonClient client = tencentConfig.createClient(primaryUId);

            // 使用JSONObject构建参数，动态传入accountId
            JSONObject params = new JSONObject();
            JSONArray customerUins = new JSONArray();
            customerUins.add(Long.parseLong(accountId));
            params.put("CustomerUin", customerUins);

            String resp = client.call("DescribeCustomerInfo", params.toJSONString());
            JSONObject response = JSONObject.parseObject(resp);
            JSONObject responseObj = response.getJSONObject("Response");
            JSONArray dataArray = responseObj.getJSONArray("Data");

            if (dataArray != null && !dataArray.isEmpty()) {
                return dataArray.getJSONObject(0);
            }
            return new JSONObject();

        } catch (Exception e) {
            throw new AppException("腾讯云账号查询异常");
        }
    }

    // 腾讯的直接累加
    public void transferCredit(String accountId, Long amount) throws Exception {
        String primaryUId = getPrimaryUId(accountId);
        CommonClient client = tencentConfig.createClient(primaryUId);

        BigDecimal bigDecimalValue = new BigDecimal(amount);
        BigDecimal dividedValue = bigDecimalValue.divide(new BigDecimal("1000000"), 6, RoundingMode.HALF_UP);
        String result = dividedValue.toPlainString();

        // 将 accountId 转换为 Long 类型（假设 accountId 是合法的数字字符串）
        Long clientUin = Long.parseLong(accountId);

        // 使用变量替换 JSON 字符串中的值
        String params = String.format("{\"AddedCredit\":%s,\"ClientUin\":%d}", result, clientUin);

        // 调用 API
        String resp = client.call("AllocateCustomerCredit", params);
    }

    public void forceQN(String accountId, Integer type) throws Exception {
        String primaryUId = getPrimaryUId(accountId);
        CommonClient client = tencentConfig.createClient(primaryUId);
        Long clientUin = Long.parseLong(accountId);
        String params = String.format("{\"ClientUin\":%d,\"Type\":%d}",  clientUin, type);
        String resp2 = client.call("ForceQN", params);
    }

    public JSONArray describeCustomerUin(String primaryUId, Integer currentPage, Integer pageSize) throws Exception {
        CommonClient client = tencentConfig.createClient(primaryUId);

        JSONObject params = new JSONObject();
        params.put("Page", currentPage);
        params.put("PageSize", pageSize);

        String resp = client.call("DescribeCustomerUin", params.toJSONString());
        JSONObject response = JSONObject.parseObject(resp);
        JSONObject responseObj = response.getJSONObject("Response");
        return responseObj.getJSONArray("Data");
    }

}
